<template>
    <div class="org-add-container">
        <el-card class="box-card" shadow="hover">
            <!-- 卡片头部 -->
            <div slot="header" class="card-header">
                <span class="header-title">{{ this.form.title }}</span>
            </div>

            <!-- 表单主体 -->
            <el-form ref="form" :model="form" label-width="100px" class="org-form" :rules="formRules">
                <!-- 第一行：机构编号 + 机构名称 -->
                <el-row :gutter="24" class="form-row">
                    <el-col :span="12">
                        <el-form-item label="机构编号" prop="orgNumber" class="form-item">
                            <el-input v-model="form.orgNumber" disabled class="form-input"
                                placeholder="系统自动生成"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="机构名称" prop="orgName" class="form-item">
                            <el-input v-model="form.orgName" class="form-input"
                                placeholder="请输入机构全称（如：XX社区卫生服务中心）"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 第二行：机构电话 + 主治医生 -->
                <el-row :gutter="24" class="form-row">
                    <el-col :span="12">
                        <el-form-item label="主治医生" prop="docterId" class="form-item">
                            <el-select v-model="form.docterId" class="form-select" placeholder="请选择主治医生"
                                @click.native.prevent="getDocters">
                                <el-option v-for="item in docters" :key="item.docterId" :label="item.docterName"
                                    :value="item.docterId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 第三行：机构地址 -->
                <el-row :gutter="24" class="form-row">
                    <el-col :span="24">
                        <el-form-item label="机构地址" prop="orgAddress" class="form-item">
                            <el-input v-model="form.orgAddress" class="form-input"
                                placeholder="请输入详细地址（如：XX市XX区XX路XX号）"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 第四行：机构状态 + 预留列 -->
                <el-row :gutter="24" class="form-row">
                    <el-col :span="12">
                        <el-form-item label="机构状态" prop="orgState" class="form-item">
                            <el-select v-model="form.orgState" class="form-select" placeholder="请选择机构状态">
                                <el-option label="启用" value="1"></el-option>
                                <el-option label="停用" value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <div class="form-empty-col"></div>
                    </el-col>
                </el-row>

                <!-- 封面图上传区域 -->
                <el-row :gutter="24" class="form-row upload-row">
                    <el-col :span="24">
                        <el-form-item label="机构封面图" class="upload-form-item">
                            <!-- 上传容器：相对定位，用于删除按钮绝对定位 -->
                            <div class="upload-wrapper">
                                <el-upload 
                                    class="avatar-uploader" 
                                    :action="serverAddress + 'uploadImg'" 
                                    :show-file-list="false"
                                    :on-success="handleAvatarSuccess" 
                                    :before-upload="beforeAvatarUpload"
                                    :disabled="isUploading"
                                >
                                    <!-- 图片预览区 -->
                                    <div class="preview-container">
                                        <!-- 已上传图片 -->
                                        <img 
                                            v-if="form.orgAvator" 
                                            :src="form.orgAvator" 
                                            class="avatar-preview"
                                            alt="机构封面图"
                                        >
                                        <!-- 未上传时的占位 -->
                                        <div v-else class="upload-placeholder">
                                            <i class="el-icon-picture-outline upload-icon"></i>
                                            <p class="upload-text">点击上传封面图</p>
                                        </div>
                                    </div>
                                    <!-- 删除按钮：仅图片存在时显示 -->
                                    <el-button 
                                        v-if="form.orgAvator"
                                        type="text" 
                                        class="delete-btn"
                                        icon="el-icon-delete"
                                        @click.stop="handleImgDelete"
                                        :loading="isDeleting"
                                    >
                                        删除
                                    </el-button>
                                </el-upload>

                                <!-- 上传提示与限制说明 -->
                                <div class="upload-hint">
                                    <span class="hint-text">支持JPG/JPEG格式，大小不超过2MB</span>
                                    <span class="hint-tip" v-if="form.orgAvator">
                                        提示：删除后需重新上传新图片
                                    </span>
                                </div>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 第五行：机构描述 -->
                <el-row :gutter="24" class="form-row">
                    <el-col :span="24">
                        <el-form-item label="机构描述" prop="orgDesc" class="form-item">
                            <el-input 
                                v-model="form.orgDesc" 
                                class="form-input" 
                                type="textarea" 
                                rows="3"
                                placeholder="请简要描述机构（如：主要提供全科诊疗、预防接种等服务）"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <br></br>
                <!-- 提交按钮 -->
                <el-form-item class="form-submit-row">
                    <el-button type="primary" @click="submitForm(form)" size="medium">
                        提交保存
                    </el-button>
                    <el-button type="default" @click="resetForm('form')" size="medium" style="margin-left: 12px">
                        重置表单
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>
import axios from 'axios';

export default {
    data() {
        return {
            serverAddress: this.serveAdd + "imageCtl/",
            docters: [],
            form: {
                title: '',
                orgId: 0,
                orgNumber: '',
                orgName: '',
                orgAddress: '',
                docterId: '',
                orgState: '1',
                orgDesc: '',
                orgAvator: ''
            },
            formRules: {
                orgName: [
                    { required: true, message: '请输入机构名称', trigger: 'blur' },
                    { min: 2, max: 50, message: '名称长度需在2-50字符之间', trigger: 'blur' }
                ],
                orgAddress: [
                    { required: true, message: '请输入机构地址', trigger: 'blur' },
                    { min: 5, max: 100, message: '地址长度需在5-100字符之间', trigger: 'blur' }
                ],
                docterId: [
                    { required: true, message: '请选择主治医生', trigger: 'change' }
                ],
                orgState: [
                    { required: true, message: '请选择机构状态', trigger: 'change' }
                ]
            },
            isUploading: false,  // 上传中状态
            isDeleting: false    // 删除中状态
        };
    },
    created() {
        this.form = this.$route.query;
        console.log(this.form.title);
        //如果是添加机构则搜索
        if(this.form.title === '添加机构'){
            this.getLastOrgNumber();
        }   
    },
    methods: {
        // 获取医生列表
        getDocters() {
            axios.get('/api/org/findDocterList')
                .then(res => {
                    if (res.data && res.data.code === 200) {
                        this.docters = res.data.data;
                    } else {
                        this.$message.warning('获取医生列表失败，请重试');
                    }
                })
                .catch(error => {
                    console.error('获取医生列表失败：', error);
                    this.$message.error('网络异常，获取医生列表失败');
                });
        },

        // 获取最新机构编号
        getLastOrgNumber() {
            axios.get('/api/org/findLastNumber')
                .then(res => {
                    if (res.data && res.data.code === 200) {
                        this.form.orgNumber = res.data.data + 1;
                    } else {
                        this.$message.warning('机构编号生成失败，将使用默认值');
                        this.form.orgNumber = Date.now().toString().slice(-6);
                    }
                })
                .catch(error => {
                    console.error('获取机构编号失败：', error);
                    this.$message.error('网络异常，机构编号生成失败');
                    this.form.orgNumber = Date.now().toString().slice(-6);
                });
        },

        // 图片上传前校验
        beforeAvatarUpload(file) {
            this.isUploading = true;
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传封面图仅支持 JPG/JPEG 格式！');
                this.isUploading = false;
                return false;
            }
            if (!isLt2M) {
                this.$message.error('上传封面图大小不能超过 2MB！');
                this.isUploading = false;
                return false;
            }
            return isJPG && isLt2M;
        },

        // 图片上传成功处理
        handleAvatarSuccess(res, file) {
            this.isUploading = false;
            if (res.code === 500) {
                this.$message({
                    message: res.message || '上传失败',
                    type: "error"
                });
                return;
            }
            if (res.code === 200) {
                this.form.orgAvator = res.data;
                this.$message.success('封面图上传成功！');
            }
        },

        // 图片删除处理
        handleImgDelete() {
            this.$confirm('确定要删除当前封面图吗？删除后需重新上传', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.isDeleting = true;
                axios.delete("api/imageCtl/deleteImg", {
                    params: {
                        imgUrl: this.form.orgAvator
                    }
                }).then(res => {
                    this.isDeleting = false;
                    if (res.data && res.data.code === 200) {
                        this.$message.success('封面图删除成功！');
                        this.form.orgAvator = '';
                    } else {
                        this.$message.warning(res.data?.msg || '删除失败，请重试');
                    }
                }).catch(error => {
                    this.isDeleting = false;
                    console.error('删除图片失败：', error);
                    this.$message.error('网络异常，删除失败');
                });
            }).catch(() => {
                this.$message.info('已取消删除');
            });
        },

        // 提交表单
        submitForm(form) {
           if(this.form.title === '添加机构'){
              axios.post('/api/org/addOrg', form).then(res => {
                if (res.data && res.data.code === 200) {
                    this.$message.success('机构添加成功！');
                    this.$router.push({ path: '/orgnazitionShow' });
                } else {
                    this.$message.warning(res.data?.msg || '机构添加失败，请重试');
                }
            }).catch(error => {
                console.error('机构添加失败：', error);
                this.$message.error('网络异常，机构添加失败');
            });
           }else{
             axios.put('/api/org/updateOrg', form).then(res => {
                if (res.data && res.data.code === 200) {
                    this.$message.success('机构修改成功！');
                    this.$router.push({ path: '/orgnazitionShow' });
                } else {
                    this.$message.warning(res.data?.msg || '机构修改失败，请重试');
                }
            }).catch(error => {
                console.error('机构修改失败：', error);
                this.$message.error('网络异常，机构修改失败');  
           });
           }
        },

        // 重置表单
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.form.orgAvator = '';  // 清空图片
            this.getLastOrgNumber();
        }
    }
};
</script>

<style scoped>
/* 外层容器样式 */
.org-add-container {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
}

/* 卡片头部样式 */
.card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 20px;
}
.header-title {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
}

/* 表单整体样式 */
.org-form {
    padding: 20px;
}

/* 表单行样式 */
.form-row {
    margin-bottom: 16px;
}

/* 表单项样式 */
.form-item {
    margin-bottom: 0;
}

/* 输入框和下拉框样式 */
.form-input,
.form-select {
    width: 100%;
    height: 36px;
}
.form-input[type="textarea"] {
    height: auto;
    resize: none;
}

/* 预留列样式 */
.form-empty-col {
    height: 36px;
}

/* 提交按钮行样式 */
.form-submit-row {
    margin-top: 24px;
    text-align: right;
    padding-right: 4px;
}

/* 上传区域样式 */
.upload-row {
    margin-bottom: 20px;
}
.upload-form-item {
    display: flex;
    align-items: flex-start;
    gap: 16px;
    margin-bottom: 0;
}

/* 上传容器样式 */
.upload-wrapper {
    position: relative;
    flex: 1;
}

/* 预览容器样式 */
.preview-container {
    width: 180px;
    height: 135px;
    border-radius: 6px;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.3s ease;
}

/* 已上传图片样式 */
.avatar-preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border: 1px solid #e5e7eb;
}

/* 未上传占位样式 */
.upload-placeholder {
    width: 100%;
    height: 100%;
    background-color: #f9fafb;
    border: 1px dashed #d1d5db;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #6b7280;
}
.upload-icon {
    font-size: 28px;
    margin-bottom: 8px;
}
.upload-text {
    font-size: 14px;
}
.upload-placeholder:hover {
    background-color: #f3f4f6;
    border-color: #409eff;
    color: #409eff;
}

/* 删除按钮样式 */
.delete-btn {
    position: absolute;
    top: -10px;
    right: -10px;
    width: 48px;
    height: 28px;
    background-color: rgba(227, 222, 222, 0.9);
    color:#000000;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
    opacity: 0;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
.upload-wrapper:hover .delete-btn {
    opacity: 1;
}
.delete-btn:hover {
    background-color: rgba(220, 38, 38, 0.9);
    color: #fff;
}
.delete-btn.is-loading .el-icon-loading {
    font-size: 16px;
}

/* 上传提示文字样式 */
.upload-hint {
    margin-top: 10px;
    font-size: 12px;
    color: #6b7280;
    display: flex;
    flex-direction: column;
    gap: 4px;
}
.hint-tip {
    color: #9ca3af;
}

/* 上传中状态样式 */
.avatar-uploader.is-disabled .preview-container {
    position: relative;
}
.avatar-uploader.is-disabled .preview-container::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.6);
}
.avatar-uploader.is-disabled .preview-container::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 24px;
    height: 24px;
    border: 2px solid #409eff;
    border-top-color: transparent;
    border-radius: 50%;
    animation: loading 1s linear infinite;
}

/* 加载动画 */
@keyframes loading {
    0% { transform: translate(-50%, -50%) rotate(0deg); }
    100% { transform: translate(-50%, -50%) rotate(360deg); }
}

/* 响应式适配 */
@media (max-width: 768px) {
    .org-add-container {
        padding: 10px;
    }
    .form-row .el-col {
        span: 24 !important;
    }
    .form-row {
        margin-bottom: 12px;
    }
    .el-form {
        label-width: 80px !important;
    }
    .preview-container {
        width: 120px;
        height: 90px;
    }
    .upload-icon {
        font-size: 20px;
    }
    .upload-text {
        font-size: 12px;
    }
}
</style>
